/*
	*********************************
				SF2D Engine
	*********************************
	Movie clip that Loads/play in a video
	and can be treated like a sprite

	By Julian Williams
	August 25, 2010
*/

#include <SFML/Graphics.hpp>

#include "helper.h"
#include "movie_clip.h"
















MovieClip::MovieClip(TheoraVideoManager *mgr)
{
	started = true;
	successfully_loaded = false;
	parent_mgr = mgr;
}


//destroy the manager pointer and 
//Nullify it, clean things up
MovieClip::~MovieClip(void)
{
	
//	parent_mgr->destroyVideoClip( clip );
	//delete parent_mgr;
//	delete clip;
}






/*
bool MovieClip::loadClip( std::string clip_location, TheoraVideoManager *mgr )
{
	
	successfully_loaded = true;

	if(mgr != NULL)
	{
		printf("[VIDEO] - clip-parent manager not set, Initializing now.\n");
		parent_mgr = mgr;
	}


    clip = parent_mgr->createVideoClip( clip_location, TH_RGBA );
	if(clip == NULL)
	{

		std::cout << "[VIDEO]-Failed to load video clip from: " << clip_location.c_str() << std::endl;
		
		successfully_loaded = false;
		//return false;
	}

	
	

	return successfully_loaded;
}//EoF
*/


//movie end?
bool MovieClip::isFinished()
{
	return clip->isDone();
}//EoF


//Tell if Video should be used
bool MovieClip::isValid()
{
	return successfully_loaded;
}

//Update Video
void MovieClip::Update(float time_update)
{
	if(successfully_loaded)
	{
		if (started)
		{
			// let's wait until the system caches up a few frames on startup
			if (clip->getNumReadyFrames() < clip->getNumPrecachedFrames()*0.5f)
				return;
			started=0;
		}

		parent_mgr->update(time_update);
	}	
}//EoF


//Draw to screen
void MovieClip::Draw( sf::RenderWindow *rendow )
{
	if(successfully_loaded)
	{
		TheoraVideoFrame* f = clip->getNextFrame();

		if (f)
		{
			current_frame.LoadFromPixels(f->getWidth(), f->getHeight(), f->getBuffer());
			//current_frame.UpdatePixels(f->getBuffer(), sf::IntRect(0, 0, f->getWidth(), f->getHeight()));
			current_frame.SetSmooth(true);

			SetImage(current_frame);

			clip->popFrame();
		}
		
		rendow->Draw(*this);
	}
}//EoF




void MovieClip::Loop(bool loop)
{
	if(successfully_loaded)
	{
		clip->setAutoRestart(loop);
	}
}//EoF



void MovieClip::togglePause()
{
	if(successfully_loaded)
	{
		if (clip->isPaused())
		{
			clip->play();
		}
		else
		{
			clip->pause(); 
		}
	}
}//EoF
